using NewLife.Caching;

namespace Aurora.TaskScheduler.DistributedLock.NewLifeRedis;

/// <summary>
/// new life redis cache
/// </summary>
public class NewLifeRedisCache
{
    private readonly NewLifeRedisFactory _factory;

    public NewLifeRedisCache(NewLifeRedisFactory factory)
    {
        _factory = factory;
    }

    private T Exec<T>(Func<FullRedis, T> func)
    {
        var redis = _factory.Get();
        return func(redis);
    }

    public void Dispose()
    {
        //不处理
    }

    public bool Add(string key, string value, TimeSpan timeSpan)
    {
        return Exec(redis => redis.Add(key, value, timeSpan.TotalSeconds.ToInt()));
    }

    public bool Add<T>(string key, T value, TimeSpan timeSpan)
    {
        return Exec(redis => redis.Add(key, value, timeSpan.TotalSeconds.ToInt()));
    }

    public T LPop<T>(string key)
    {
        return Exec(redis => redis.LPOP<T>(key));
    }

    public T Get<T>(string key)
    {
        return Exec(redis => redis.Get<T>(key));
    }

    public long Del(string key)
    {
        return Exec(redis => redis.Remove(key));
    }

    /// <summary>
    /// 分布式锁
    /// </summary>
    /// <param name="key"></param>
    /// <param name="timeout"></param>
    /// <returns></returns>
    public bool AcquireLock(string key, int timeout)
    {
        return Exec(redis => redis.AcquireLock(key, timeout) != null);
    }
}